package com.thb.pay.core.interceptor;

import com.thb.pay.core.utils.Constant;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class GlobalLocaleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Locale locale = Locale.US;
        String lang = request.getParameter(Constant.LOCALE_REQUEST_PARAM_LANG);
        if (!StringUtils.isEmpty(lang)) {
            locale = org.apache.commons.lang3.LocaleUtils.toLocale(lang);
        } else {
            String activeLanguage = request.getHeader(Constant.HEADER_ACTIVE_LANGUAGE);
            if (!StringUtils.isEmpty(activeLanguage)) {
                locale = org.apache.commons.lang3.LocaleUtils.toLocale(activeLanguage);
            }
        }
        LocaleContextHolder.setLocale(locale);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LocaleContextHolder.resetLocaleContext();
    }


}
